var parse = require('co-busboy');
var path = require('path');
var fs = require('fs');
var crypto = require('crypto');
var uuid = require("node-uuid");
var hash = crypto.createHash('md5');
var util = require('../lib/utilx');
var auth = require("../helpers/auth");
var models = require("../models/index");
const Story = models.Story;

module.exports = (router) => {
    router.post('/api/token/upload',function * (){
        var ctx = this;
        var userID = (yield auth.user(this)).id;
        if( !this.request.is('multipart/*')) return yield next;

        var part,filename = '';
        var parts = parse(this,{
            checkFile: function (fieldname, file, _filename) {
                filename = _filename;
            }
        });
        while(part = yield parts){
            if(part.length){
                if(part[0] === 'name'){
                    // filename = part[1];
                }
            }else{
                var prefix = util.getUniqueStr(6) + '_';
                filename = prefix + filename;
                var file_directory = path.join(__dirname,'../public/upload/file');
                var file_path = path.join(file_directory,filename);
                try{
                    fs.accessSync(file_directory);
                }catch (err){
                    fs.mkdirSync(file_directory);
                    ctx.body = 'false';
                    return;
                }
                var is_exist = fs.existsSync(file_path);
                if(is_exist) {
                    ctx.body = 'false';
                    return;
                }
                part.pipe(fs.createWriteStream(path.join(__dirname,'../public/upload/file',filename)));
            }
        }
        // create md5
        const input = fs.readFileSync(path.join(__dirname,'../public/upload/file',filename));
        const md5 = hash.update(input).digest('hex');
        yield Story.create({
            id: uuid.v4(),
            title : "用户上传图片",
            flags: "",
            content: "打印机图片",
            location : 'http://123.206.80.54:3030/upload/file/' + filename,
            AuthorID: userID
        })
        ctx.body = {
            md5,
            location :　'http://123.206.80.54:3030/upload/file/' + filename
        }
    });
};

